<template>
	<view class="order-page">
		<template v-if="userInfo.id">
			<view class="tabs">
				<uv-tabs :list="tabList" :scrollable="true" lineColor="#FFC434" @click="tabChange"></uv-tabs>
			</view>
			<common-list :isDataEmpty="tableData.length === 0" :status="status" emptyTop="200rpx">
				<template #list>
					<view>
						<view class="order-list">
							<view class="order-item" v-for="(item, index) in tableData" :key="index"
								@click="handDetail(item, index)">
								<view class="status">{{ item.statusName }}</view>
								<view class="car-info">
									<image :src="item.coverPlan" mode="aspectFill"></image>
									<view class="info">
										<view class="name">{{ item.productName }} </view>
										<view class="desc">
											<text>{{ item.brand }}</text>
											<text>{{ item.model }}</text>
										</view>
										<view class="tags">
											<view class="tag" v-if="item.powerType">{{ item.powerType }}</view>
											<view class="tag" v-if="item.mileage">{{ item.mileage }}</view>
											<view class="tag" v-if="item.fineness">{{ item.fineness }}</view>
											<view class="tag" v-if="item.chargingMode">{{ item.chargingMode }}</view>
										</view>
									</view>
								</view>
								<view class="grid">
									<view class="grid-item">
										<view class="value">
											<text>{{ item.schemes.lease }}</text>
											<text>个月</text>
										</view>
										<view class="label">期数</view>
									</view>
									<view class="grid-item">
										<view class="value">
											<text>{{ item.schemes.rent }}</text>
											<text>元/月</text>
										</view>
										<view class="label">价格</view>
									</view>
									<view class="grid-item">
										<view class="value">
											<text>{{ item.schemes.deposit }}</text>
											<text>元</text>
										</view>
										<view class="label">押金(可退)</view>
									</view>
								</view>
								<view class="order-bottom">
									<view class="tip">
										<template v-if="item.status === 'UNDERWAY'">
											<text v-if="item.isYuqi" style="color: orangered;">[逾期]</text>
											<text
												v-if="item.leaseOrder">{{ item.leaseOrder.leaseName }}分期账单于{{ item.leaseOrder.refundTime }}还</text>
										</template>
									</view>
									<view class="btns">
										<template v-if="item.status === 'UNPAID'">
											<button class="cu-btn" @click.stop="handCancelPay(index)">取消订单</button>
											<button class="cu-btn cu-btn-a"
												@click.stop="handPay(item, index)">立即支付</button>
										</template>
										<template v-else-if="item.status === 'CONFIRM'">
											<button class="cu-btn" @click.stop="handCancel(index)">取消订单</button>
											<button class="cu-btn cu-btn-a" @click.stop="handPhone(item)">联系商家</button>
										</template>
										<template v-else-if="item.status === 'UNDERWAY'">
											<button v-if="item.isLease" class="cu-btn cu-btn-a"
												@click.stop="handLease(index)">续租</button>
											<template v-if="item.productType === 'DEALER'">
												<button class="cu-btn cu-btn-a"
													@click.stop="handBill(item, index)">查看账单</button>
											</template>
											<template v-else>
												<button class="cu-btn cu-btn-a"
													@click.stop="handDetail(item, index)">查看详情</button>
											</template>
										</template>
										<template v-else-if="item.status === 'CONFIRM_DEPOSIT_REFUND'">
											<button class="cu-btn" @click.stop="handAppeal(item, index)">申诉</button>
											<button class="cu-btn cu-btn-a" @click.stop="handOver(index)">确认完成</button>
										</template>
										<template v-else-if="item.status === 'APPEAL'">
											<button class="cu-btn" @click.stop="handCalcelApp(index)">取消申诉</button>
										</template>
										<template v-else-if="item.status === 'DISPOSE_APPEAL'">
											<button class="cu-btn cu-btn-a" @click.stop="handOver(index)">确认完成</button>
										</template>
									</view>
								</view>
							</view>
						</view>
					</view>
				</template>
			</common-list>
		</template>
		<template v-else>
			<view class="no-login" @click="handLogin">
				<text class="cuIcon cuIcon-safe"></text>
				<view class="tip">
					请先登录
				</view>
			</view>
		</template>

		<diao-pop ref="diaoRef" :title="title" :tip="tip" :confirmText="confirmText" @confirm="handConfirm" />
		<bill-pop ref="billRef" @paySuccess="paySuccess" />
		<tabbar-bottom :curren="2" />
		<uv-modal ref="modal" show-cancel-button confirm-color="#FF9113" @confirm="handConfirm" width="550rpx">
			<view style="line-height: 100rpx;">{{ tip }}</view>
		</uv-modal>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		onLoad,
		onShow,
		onReachBottom,
		onPullDownRefresh,
	} from "@dcloudio/uni-app";
	import {
		userList
	} from '@/hooks/userList.js'
	import {
		doList,
		doCancel,
		doDetail,
		doCancelApp,
		doOver,
		doLease,
		doCancelPay,
		doOrderPay
	} from '@/apis/order.js'
	import {
		getDate,
		timeIncludes
	} from '@/utils/index.js'
	import {
		useAppsStore
	} from '@/stores/modules/app.js'
	import {
		storeToRefs
	} from 'pinia'
	import TabbarBottom from '@/components/tabbar/TabbarBottom.vue'
	import CommonList from '@/components/commonList/list.vue'
	import DiaoPop from '@/components/DiaoPop.vue'
	import BillPop from '@/components/BillPop.vue'

	const useStore = useAppsStore()
	const {
		getUserInfo: userInfo
	} = storeToRefs(useStore)

	const billRef = ref()
	const handBill = (row, index) => {
		oldIndex = index
		billRef.value.handOpen(row)
	}
	const paySuccess = () => {
		rowChange(oldIndex)
	}

	const handAppeal = (row, index) => {
		goDetail = true
		uni.navigateTo({
			url: `/pagesA/order/appeal?id=${row.id}`,
			events: {
				successEvent: () => {
					rowChange(index)
				}
			}
		})
	}

	const handLogin = () => {
		uni.navigateTo({
			url: '/pagesA/login/login'
		})
	}

	let type = 'cancel'
	let oldIndex = 0
	const modal = ref()
	const diaoRef = ref()
	const tip = ref('')
	const title = ref('')
	const confirmText = ref('')
	const handCancel = (index) => {
		type = 'cancel'
		oldIndex = index
		tip.value = '确认要取消订单吗?'
		modal.value.open()
	}
	const handCancelPay = (index) => {
		type = 'cancelPay'
		oldIndex = index
		tip.value = '确认要取消订单吗?'
		modal.value.open()
	}
	const handPay = async (row, index) => {
		oldIndex = index
		const {
			code,
			message
		} = await doOrderPay(row.id)
		if (code !== 200) {
			uni.hideLoading()
			uni.$uv.toast(message)
			return
		}
		wxPay(JSON.parse(message))
	}
	const wxPay = (payInfo) => {
		uni.hideLoading()
		const orderInfo = {
			provider: 'wxpay', // 服务提提供商
			timeStamp: payInfo.timeStamp, // 时间戳
			nonceStr: payInfo.nonceStr, // 随机字符串
			package: payInfo.package,
			signType: payInfo.signType, // 签名算法
			paySign: payInfo.paySign, // 签名
		};
		uni.requestPayment({
			provider: 'wxpay',
			...orderInfo,
			success: (res) => {
				uni.$uv.toast('支付成功')
				rowChange(oldIndex)
			},
			fail: (err) => {
				uni.$uv.toast('支付失败')
			}
		});
	}
	const handCalcelApp = (index) => {
		type = 'app'
		oldIndex = index
		tip.value = '确认要取消申述吗?'
		modal.value.open()
	}
	const handOver = (index) => {
		type = 'over'
		oldIndex = index
		title.value = '确定完成吗?'
		tip.value = '请仔细查看退回押金信息\n确认后将无法撤回'
		confirmText.value = '确认'
		diaoRef.value.open()
	}
	const handLease = (index) => {
		type = 'lease'
		oldIndex = index
		title.value = '续租提示'
		tip.value = '您的租车方案即将到期\n是否要续期？'
		confirmText.value = '续租'
		diaoRef.value.open()
	}
	const handConfirm = async () => {
		if (type === 'cancel') {
			await doCancel(tableData.value[oldIndex].id)
			uni.$uv.toast('已取消')
			rowChange(oldIndex)
		} else if (type === 'cancelPay') {
			await doCancelPay(tableData.value[oldIndex].id)
			uni.$uv.toast('已取消')
			rowChange(oldIndex)
		} else if (type === 'app') {
			await doCancelApp(tableData.value[oldIndex].id)
			uni.$uv.toast('已取消')
			rowChange(oldIndex)
		} else if (type === 'over') {
			await doOver(tableData.value[oldIndex].id)
			uni.$uv.toast('已完成')
			rowChange(oldIndex)
		} else if (type === 'lease') {
			await doLease(tableData.value[oldIndex].id)
			uni.$uv.toast('续租成功')
			rowChange(oldIndex)
		}
	}

	const tabList = ref([{
		name: '全部',
		value: ''
	}, {
		name: '待支付',
		value: 'UNPAID'
	}, {
		name: '待确定',
		value: 'CONFIRM'
	}, {
		name: '进行中',
		value: 'UNDERWAY'
	}, {
		name: '退押金',
		value: 'DEPOSIT'
	}, {
		name: '已完成',
		value: 'FINISH'
	}])
	const curren = ref(0)
	const tabChange = (e) => {
		curren.value = e.index
		queryForm.value.status = e.value
		onRefresh()
	}

	const handDetail = (e, index) => {
		goDetail = true
		uni.navigateTo({
			url: `/pagesA/order/detail?id=${e.id}`,
			events: {
				backInfo: (info) => {
					if (info.status !== e.status) {
						rowChange(index)
					} else if (info.status === 'UNDERWAY' && info.leaseOrder.leaseName !== e.leaseOrder
						.leaseName) {
						rowChange(index)
					}
				}
			}
		})
	}

	const handPhone = (e) => {
		goDetail = true
		uni.makePhoneCall({
			phoneNumber: e.merchantPhone
		})
	}
	/**
	 * 
	 * 列表数据
	 * */
	const statusEnum = {
		UNPAID: '待支付',
		CANCEL: '已取消',
		CONFIRM: '待确认',
		UNDERWAY: '进行中',
		DEPOSIT_REFUND: '商家处理中',
		CONFIRM_DEPOSIT_REFUND: '待确认退还',
		APPEAL: '申诉中',
		DISPOSE_APPEAL: '平台已处理',
		FINISH: '已完成',
	}
	const rowChange = async (index) => {
		const oldInfo = tableData.value[index]
		let data = await doDetail(tableData.value[index].id)
		data = getItem(data)
		if (curren.value === 0) {
			tableData.value[index] = data
		} else if (oldInfo.status !== data.status) {
			tableData.value.splice(index, 1)
		} else {
			tableData.value[index] = data
		}
	}
	const getItem = (row) => {
		row.statusName = statusEnum[row.status]
		row.schemes = JSON.parse(row.schemes)
		row.isLease = false
		if (row.status === 'UNDERWAY') {
			const starTime = new Date(getDate(row.endTime, -10)).getTime()
			const endTIme = new Date(row.endTime.replace(/-/g, '/')).getTime()
			const nowTime = new Date().getTime()
			if (nowTime >= starTime && nowTime <= endTIme) {
				row.isLease = true
			}
			row.isYuqi = false
			if (row.leaseOrder) {
				if (new Date() > new Date(row.leaseOrder.refundTime.replace(/\//g, "-"))) {
					row.isYuqi = true
				}
			}
		}
		return row
	}
	const getApi = async (params) => {
		if (!params.status) {
			delete params.status
		}
		const res = await doList(params)
		res.records = res.records.map(el => {
			return getItem(el)
		})
		return res
	}
	const {
		tableData,
		status,
		fetchData,
		onBottom,
		onRefresh,
		queryForm
	} = userList({
		apis: {
			getApi
		},
		initForm: {
			status: ''
		}
	})

	onPullDownRefresh(() => {
		if (userInfo.value?.id) {
			onRefresh()
		} else {
			uni.$uv.toast('请先登录')
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 500)
		}
	})
	onReachBottom(() => {
		onBottom()
	})

	onLoad(async () => {
		uni.hideTabBar()
	})
	let goDetail = false
	onShow(() => {
		if (!userInfo.value?.id) {
			return
		}
		if (goDetail) {
			goDetail = false
			return
		}
		onRefresh()
	})
</script>

<style lang="scss" scoped>
	.order-page {
		min-height: 100vh;
		background: #F5F5F5;

		.no-login {
			padding-top: 80rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			.cuIcon {
				font-size: 120rpx;
				color: gray;
			}

			.tip {
				margin-top: 20rpx;
				font-size: 28rpx;
				color: gray;
			}
		}

		.tabs {
			position: sticky;
			top: 0;
			z-index: 3;
			background-color: #fff;
		}

		.order-list {
			padding: 20rpx 24rpx;

			.order-item {
				background-color: #fff;
				border-radius: 16rpx;
				padding: 24rpx;
				box-sizing: border-box;
				position: relative;

				&:not(:first-child) {
					margin-top: 40rpx;
				}

				.status {
					position: absolute;
					right: 24rpx;
					top: 24rpx;
					font-size: 26rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #F58701;
				}

				.car-info {
					display: flex;
					align-items: center;

					image {
						width: 160rpx;
						height: 160rpx;
						border-radius: 16rpx;
					}

					.info {
						flex: 1;
						margin-left: 24rpx;

						.name {
							font-size: 30rpx;
							font-family: PingFang SC-Bold, PingFang SC;
							font-weight: bold;
							color: #333333;
						}

						.desc {
							margin-top: 8rpx;
							font-size: 24rpx;
							font-family: PingFang SC-Regular, PingFang SC;
							font-weight: 400;
							color: #999999;
						}

						.tags {
							margin-top: 14rpx;
							display: flex;

							.tag {
								font-size: 24rpx;
								font-family: PingFang SC-Regular, PingFang SC;
								font-weight: 400;
								color: #999999;
								padding: 6rpx 12rpx;
								background: #F5F5F5;
								border-radius: 4rpx;

								&:not(:first-child) {
									margin-left: 8rpx;
								}
							}
						}
					}
				}

				.grid {
					margin-top: 32rpx;
					background: #F8F8F8;
					border-radius: 16rpx;
					padding: 32rpx 40rpx;
					display: flex;
					justify-content: space-between;

					&-item {
						.value {
							text {
								font-size: 24rpx;
								font-family: PingFang SC-Regular, PingFang SC;
								font-weight: 400;
								color: #FF4E00;

								&:first-child {
									font-size: 32rpx;
								}
							}
						}

						.label {
							margin-top: 10rpx;
							font-size: 26rpx;
							font-family: PingFang SC-Regular, PingFang SC;
							font-weight: 400;
							color: #666666;
						}
					}
				}

				.order-bottom {
					margin-top: 32rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;

					.tip {
						flex: 1;
						margin-right: 20rpx;
						font-size: 26rpx;
						font-family: PingFang SC-Regular, PingFang SC;
						font-weight: 400;
						color: #F57B01;
					}

					.btns {
						display: flex;
						align-items: center;

						.cu-btn {
							width: 192rpx;
							height: 74rpx;
							background: #F5F5F5;
							border-radius: 16rpx;
							font-size: 30rpx;
							font-family: PingFang SC-Medium, PingFang SC;
							font-weight: 500;
							color: #333333;

							&:not(:last-child) {
								margin-right: 20rpx;
							}

							&-a {
								background: #FFC434;
								color: #333333;
							}
						}
					}
				}
			}

		}
	}
</style>